import React, { useState, useEffect } from 'react';
import Sidebar from './components/Sidebar';
import Dashboard from './components/Dashboard';
import EmployeeList from './components/EmployeeList';
import AttendanceTracker from './components/AttendanceTracker';
import PayrollManager from './components/PayrollManager';
import Login from './components/Login';
import * as api from './services/api';
import type { Employee, AttendanceRecord, PayrollRecord } from './types';
import { View } from './types';


const App: React.FC = () => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [isLoading, setIsLoading] = useState(true);
  const [currentView, setCurrentView] = useState<View>(View.Dashboard);
  const [employees, setEmployees] = useState<Employee[]>([]);
  const [attendance, setAttendance] = useState<AttendanceRecord[]>([]);
  const [payroll, setPayroll] = useState<PayrollRecord[]>([]);

  const fetchData = async () => {
    try {
      const [employeesData, attendanceData, payrollData] = await Promise.all([
        api.getEmployees(),
        api.getAttendance(),
        api.getPayroll(),
      ]);
      setEmployees(employeesData);
      setAttendance(attendanceData);
      setPayroll(payrollData);
    } catch (error) {
        console.error("Failed to fetch data:", error);
        // If any fetch fails, treat as not authenticated
        setIsAuthenticated(false);
        await api.logout();
    }
  };

  useEffect(() => {
    const checkAuthStatus = async () => {
      try {
        const authStatus = await api.checkAuth();
        if (authStatus.isAuthenticated) {
          setIsAuthenticated(true);
          await fetchData();
        }
      } catch (error) {
        console.error("Authentication check failed:", error);
      } finally {
        setIsLoading(false);
      }
    };
    checkAuthStatus();
  }, []);

  const handleLoginSuccess = async () => {
    setIsAuthenticated(true);
    await fetchData();
  };
  
  const handleLogout = async () => {
    await api.logout();
    setIsAuthenticated(false);
    setEmployees([]);
    setAttendance([]);
    setPayroll([]);
  };

  const refreshEmployees = async () => {
    const employeesData = await api.getEmployees();
    setEmployees(employeesData);
  }

  const renderView = () => {
    switch (currentView) {
      case View.Dashboard:
        return <Dashboard employees={employees} attendance={attendance} payroll={payroll} />;
      case View.Employees:
        return <EmployeeList employees={employees} onDataChange={refreshEmployees} />;
      case View.Attendance:
        return <AttendanceTracker attendance={attendance} employees={employees} />;
      case View.Payroll:
        return <PayrollManager payroll={payroll} employees={employees} />;
      default:
        return <Dashboard employees={employees} attendance={attendance} payroll={payroll} />;
    }
  };

  if (isLoading) {
    return (
        <div className="flex h-screen w-full items-center justify-center bg-slate-100">
            <div className="text-xl font-semibold text-slate-700">正在加载...</div>
        </div>
    );
  }

  if (!isAuthenticated) {
    return <Login onLoginSuccess={handleLoginSuccess} />;
  }

  return (
    <div className="flex h-screen bg-slate-100 font-sans">
      <Sidebar currentView={currentView} setCurrentView={setCurrentView} onLogout={handleLogout} />
      <main className="flex-1 overflow-y-auto p-8">
        {renderView()}
      </main>
    </div>
  );
};

export default App;